<?php
require(ROOT . '/controllers/CommonController.class.php');

class ChatController extends CommonController {

	public function __construct() {
		parent::__construct(__CLASS__);
	}

	public function indexAction() {
		$userId = (int)$_SESSION['reading_user_id'];

		$userModel = new Model('user',$this->db);

		$user = $userModel->find($userId);

		$this->assign('user',$user);
		
		$users = $userModel->query();
		
		$this->assign('users',$users);

		$this->rend('index');
	}

	public function receiveAction() {
		$lastTime = requestGet('lastTime');

		if ($lastTime == 0) {
			$lastTime = strtotime('today');
		}

		$userId = (int)$_SESSION['reading_user_id'];
		
		$sql = "SELECT 
			t.nick as `to`,
			f.nick as `from`,
			c.content as content,
			c.created_at as created_at 
		FROM chat c 
		LEFT JOIN user t ON c.`to`=t.`id` 
		LEFT JOIN user f ON c.`from`=f.`id` 
		WHERE c.created_at>{$lastTime} AND c.`to`={$userId} OR c.`from`={$userId}";
		
		if($userId != 1){
			//$sql .= " AND c.`from`=1;";
		}
		
		$data = $this->db->query($sql);

		$this->json(0, '', array('records' => $data, 'time' => time()));
	}

	public function sendAction() {
		$content = requestPost('content');

		$userId = (int)$_SESSION['reading_user_id'];

		$data = array(
			'ip' => ip2long($_SERVER['REMOTE_ADDR']),
			'from' => $userId,
			'content' => strip_tags($content),
			'created_at' => time()
		);

		$data['to'] = $userId == 1?(int)$_POST['to']:1;
		
		if($data['to'] == $data['from']){
			$this->json(0,'不能发消息给自己');
		}

		$chatModel = new Model('chat', $this->db);

		if ($chatModel->insert($data)) {
			$this->json(0);
		} else {
			$this->json(1);
		}
	}

	public function historyAction() {
		$sql = "select * from chat order by created_at desc";

		$data = $this->db->query($sql);

		$this->json(0, '', array('records' => $data, 'time' => time()));
	}

	public function clearAction() {
		$sql = "delete from chat";

		$this->db->exec($sql);

		$this->json(0);
	}

}
